package pers.kw.service;

import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.kw.dao.OauthClientDetailsDao;
import pers.kw.entity.OauthClientDetailsDO;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class OauthClientDetailsService {

    @Resource
    private OauthClientDetailsDao oauthClientDetailsDao;

    public List<OauthClientDetailsDO> list() {
        return oauthClientDetailsDao.findAll();
    }

    @Transactional(rollbackFor = Exception.class)
    public void add(OauthClientDetailsDO clientDetailsDO) {
        OauthClientDetailsDO detailsDO = oauthClientDetailsDao.findByClientId(clientDetailsDO.getClientId());
        if (detailsDO != null) {
            throw new RuntimeException("应用信息已存在");
        }
        //秘钥加密
        BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
        clientDetailsDO.setClientSecret(bCryptPasswordEncoder.encode(clientDetailsDO.getClientSecret()));
        clientDetailsDO.setCreateTime(new Date());
        //scope默认值
        clientDetailsDO.setScope("all");
        oauthClientDetailsDao.save(clientDetailsDO);
    }

    @Transactional(rollbackFor = Exception.class)
    public void update(OauthClientDetailsDO clientDetailsDO) {
        OauthClientDetailsDO detailsDO = oauthClientDetailsDao.findByClientId(clientDetailsDO.getClientId());
        if (detailsDO == null) {
            throw new RuntimeException("应用信息不存在");
        }
        detailsDO.setUpdateTime(new Date());
        detailsDO.setAutoapprove(clientDetailsDO.getAutoapprove());
        detailsDO.setClientName(clientDetailsDO.getClientName());
        detailsDO.setWebServerRedirectUri(clientDetailsDO.getWebServerRedirectUri());
        detailsDO.setAuthorizedGrantTypes(clientDetailsDO.getAuthorizedGrantTypes());
        oauthClientDetailsDao.save(detailsDO);
    }

    @Transactional(rollbackFor = Exception.class)
    public Integer delete(String clientId) {
        return oauthClientDetailsDao.deleteByClientId(clientId);
    }
}
